package crane.bomb;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/**
 * 
 * @author crane
 *
 */
public class BombFrame extends MainFrame{

    BombFrame(){
        String[] sValue = new BombAction().createArray(BombFrame.SIZE_STRING[0], BombFrame.SIZE_STRING[1]);
        String[] lValue = new BombAction().createArray(BombFrame.LEVEL_STRING[0], BombFrame.LEVEL_STRING[1]);
        int len = Integer.parseInt(sValue[BombFrame.DEFAULT_SIZE_INDEX]);
        int level = Integer.parseInt(lValue[BombFrame.DEFAULT_LEVEL_INDEX]);
        this.xLength = len;
        this.yLength = len;
        this.level = level;
    }


    /**
     * @param mBean
     */
    void setMainBean(MainBean mBean) {
        this.mBean = mBean;        
    }
    
    /**
     * @return mBean
     */
    MainBean getMainBean() {
        return this.mBean;
    }
    
    /*
     * mBean
     */
    private MainBean mBean;
    
    /**
     * xCombobox
     */
    protected JComboBox xCombobox = null;
    
    /**
     * yCombobox
     */
    protected JComboBox yCombobox = null;
    
    /**
     * levelCombobox
     */
    protected JComboBox levelCombobox = null;
    
    /**
     * start Game Button
     */
    protected JButton startButton = null;
    
    /**
     * Show Time Field
     */
    protected TimerText timerText = null;
    
    /**
     * numLeftJTextField
     */
    protected JTextField remainText = null;
    
    /**
     * SIZE_STRING
     */
    public static final int[] SIZE_STRING = {5, 20};
    
    /**
     * DEFAULT_SIZE_INDEX
     */
    public static final int DEFAULT_SIZE_INDEX = 3;
    
    /**
     * LEVEL_STRING
     */
    public static final int[] LEVEL_STRING = {1, 8};
    
    /**
     * DEFAULT_LEVEL_INDEX
     */
    public static final int DEFAULT_LEVEL_INDEX = 2;
    
    /**
     * DEFAULT_BUTTON_WIDTH
     */
    public static final int DEFAULT_BUTTON_WIDTH = 30;
    
    /**
     * DEFAULT_BUTTON_HEIGHT
     */
    public static final int DEFAULT_BUTTON_HEIGHT = 30;

    /**
     * Paint Frame
     * 
     */
    protected void paintFrame(JFrame frame) {

        Container cp = frame.getContentPane();
        frame.setTitle("Find Bombs");
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout(1, 3));
        JPanel panel = initUpPanel();
        mainPanel.add(panel, BorderLayout.NORTH);

        panel = initMidPanel();
        mainPanel.add(panel, BorderLayout.CENTER);
        
        panel = initDownPanel();
        JPanel downPanel = new JPanel();
        downPanel.setLayout(new FlowLayout(1));
        downPanel.add(panel);
        mainPanel.add(downPanel, BorderLayout.SOUTH);
        
        JScrollPane scroll = new JScrollPane(mainPanel);
        scroll.setAutoscrolls(false);
        cp.add(scroll);

        return;
    }
    
    /**
     * initUpPanel
     * 
     * @return JPanel
     */
    private JPanel initUpPanel() {
        BombAction action = new BombAction();
        String[] sValue = action.createArray(SIZE_STRING[0], SIZE_STRING[1]);
        String[] lValue = action.createArray(LEVEL_STRING[0], LEVEL_STRING[1]);
        int dsIdx = DEFAULT_SIZE_INDEX;
        int dlIdx = DEFAULT_LEVEL_INDEX;
        int x = this.xLength;
        if (x < 1) {
            x = Integer.parseInt(sValue[dsIdx]);
            this.xLength = x;
        }
        int y = this.getYLength();
        if (y < 1) {
            y = Integer.parseInt(sValue[dsIdx]);
            this.yLength = y;
        }
        int iLevel = this.level;
        if (iLevel < 1) {
            iLevel = Integer.parseInt(lValue[dlIdx]);
            this.level = iLevel;
        }

        JPanel panel = new JPanel(true);
        panel.setName("UP_PANEL");
        Box boxBase = Box.createHorizontalBox();
        
        // label:  Size
        JLabel label = new JLabel("Size: ");
        label.setPreferredSize(new Dimension(30, 25));
        boxBase.add(label);

        // Text: Size
        xCombobox = new JComboBox(sValue);
        xCombobox.setName("X_LEN");
        xCombobox.setSelectedItem("" + x);
        xCombobox.setPreferredSize(new Dimension(40, 25));
        xCombobox.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
                xLength = Integer.parseInt(xCombobox.getSelectedItem().toString());
            }
        });
        boxBase.add(xCombobox);

        label = new JLabel("X");
        label.setPreferredSize(new Dimension(10, 25));
        boxBase.add(label);

        yCombobox = new JComboBox(sValue);
        yCombobox.setName("Y_LEN");
        yCombobox.setSelectedItem("" + y);
        yCombobox.setPreferredSize(new Dimension(40, 25));
        yCombobox.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
                yLength = Integer.parseInt(yCombobox.getSelectedItem().toString());
            }
        });
        boxBase.add(yCombobox);
        boxBase.add(Box.createHorizontalStrut(20));

        // Label: Level
        label = new JLabel("Level:");
        label.setPreferredSize(new Dimension(35, 25));
        boxBase.add(label);

        levelCombobox = new JComboBox(lValue);
        levelCombobox.setName("LEVEL");
        levelCombobox.setSelectedItem("" + iLevel);
        levelCombobox.setPreferredSize(new Dimension(40, 25));
        levelCombobox.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
                level = Integer.parseInt(levelCombobox.getSelectedItem().toString());
            }
        });
        boxBase.add(levelCombobox);
        panel.add(boxBase);
        panel.setVisible(true);
        return panel;
    }

    /**
     * initUpPanel
     * 
     * @return JPanel
     */
    private JPanel initMidPanel() {

        JPanel panel = new JPanel(true);
        panel.setName("MID_PANEL");
        panel.setLayout(new BorderLayout());
        timerText = new TimerText();
        panel.add(timerText, BorderLayout.WEST);
        
        JPanel midPanel = new JPanel();
        midPanel.setLayout(new FlowLayout(1, 1, 1));
        startButton = new JButton();
        startButton.setPreferredSize(new Dimension(35, 35));
        startButton.setIcon(FileUtil.getImage("/images/0.gif"));
        startButton.setPressedIcon(FileUtil.getImage("/images/1.gif"));
        startButton.setName("START_BUTTON");
        startButton.addActionListener(this);        
        midPanel.add(startButton);
        panel.add(midPanel, BorderLayout.CENTER);

        remainText = new JTextField();
        remainText.setFont(new Font("Arial", Font.BOLD, 24));
        remainText.setPreferredSize(new Dimension(40, 35));
        remainText.setHorizontalAlignment(0);
        remainText.setEnabled(false);
        remainText.setFocusable(false);
        remainText.setDisabledTextColor(BombColor.C_TEXT_READONLY_FORE);
        remainText.setBackground(BombColor.C_TEXT_READONLY_BACK);
        panel.add(remainText, BorderLayout.EAST);
        
        panel.setVisible(true);
        return panel;
    }

    /**
     * get Panel
     * 
     * @return JPanel
     */
    private JPanel initDownPanel() {

        if (this.xLength < 1) {
            this.xLength = 10;
        }

        if (this.yLength < 1) {
            this.yLength = 10;
        }

        if (this.level == 0) {
            this.level = 2;
        }

        JPanel panel = new JPanel();
        panel.setName("DOWN_PANEL");
        panel.setLayout(new GridLayout(this.xLength, this.yLength, 0, 0));

        JButton button = null;
        JButton[] buttonArray = new JButton[this.xLength * this.yLength];
        for (int i = 0; i < this.xLength * this.yLength; i++) {
            button = new JButton();
            button.setBackground(BombColor.C_BTN_INTI);
            button.setPreferredSize(new Dimension(DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT));
            button.setName(String.valueOf(i));
            button.addActionListener(this);
            button.addMouseListener(this);
            buttonArray[i] = button;
        }
        this.buttonArray = buttonArray;

        for (int i = 0; i < buttonArray.length; i++) {
            panel.add(buttonArray[i]);
        }
        return panel;
    }
    
    /**
     * init Value of the Frame
     *
     */
    protected void initValues(){
        this.remainText.setText(this.bombArray.getBombRemain() + "");
    }
    
    /**
     * isTimeout
     * @return boolean
     */
    public boolean isTimeOut(){
        // Timeout 
        if (this.timerText.isTimeOut()){
            BombAction action = new BombAction();
            action.setBombed(this);
            // showDialog("You cost too much time!\nPlease restart the game!");
            new BombAction().showModallog(this.mBean.getFrame(), "Message", "You cost too much time!\nPlease restart the game!");
            return true;
        }
        return false;
    }
    
    /**
     * X length
     */
    private int xLength = 0;

    /**
     * Y length
     */
    private int yLength = 0;

    /**
     *  Level
     */
    private int level = 0;

    /**
     * 
     * @return int
     */
    protected int getXLength() {
        return this.xLength;
    }
    
    /**
     * 
     * @param len
     */
    protected void setXLength(int len){
        this.xLength = len;
    }

    /**
     * 
     * @return int
     */
    protected int getYLength() {
        return this.yLength;
    }
    
    /**
     * 
     * @param len
     */
    protected void setYLength(int len){
        this.yLength = len;
    }

    /**
     * 
     * @return int
     */
    protected int getLevel() {
        return this.level;
    }
    
    /**
     * 
     * @param len
     */
    protected void setLevel(int len){
        this.level = len;
    }
    
    /**
     * getScore
     * @return String
     */
    protected String getScore(){
        String time = this.timerText.getText();
        return "" + Integer.parseInt(time);
    }

    private JButton[] buttonArray = null;

    /**
     * 
     * @return buttonArray
     */
    protected JButton[] getButtonArray() {
        return this.buttonArray;
    }
    

    /**
     * 
     * @param id
     * @return JButton
     */
    protected JButton getButton(int id) {
        return this.buttonArray[id];
    }    

    
    /**
     * BOMB
     */
    private BombArray bombArray = null;
    
    /**
     * @return the _yLength
     */
    protected BombArray getBombArray() {
        return this.bombArray;
    }

    /**
     * @param bomb
     */
    protected void setBombArray(BombArray bomb) {
        this.bombArray = bomb;
        initValues();
    }
    
    /**
     * Save Score into XML
     *
     */
    private void doSaveScore(){
        BombAction action = new BombAction();
        int level = this.level;
        String time = getScore();
        boolean saveFlg = action.checkSaveScore(level, Integer.parseInt(time));        
        if (saveFlg){
            action.showInputNameWindow(mBean);
        }        
    }

    /**
     * MOUSE CLICKED
     */
    public void mouseClicked(MouseEvent e) {
        Object obj = e.getSource();
        BombAction action = new BombAction();
        if (obj instanceof JButton) {
            JButton button = (JButton) obj;
            String bId = button.getName();
            try {
                MainBean mBean = getMainBean();
                JFrame frame = mBean.getFrame();
                BombFrame bombFrame = mBean.getBombFrame();
                
                int id = Integer.parseInt(bId);
                int mod = e.getModifiers();
                
                // Timeout 
                if (bombFrame.isTimeOut()){
                    return;
                }
                
                if (mod == InputEvent.BUTTON1_MASK) {
                   
                    if (action.checkGameOvered(bombFrame)) {
                        return;
                    }
                    
                    // Timer start
                    bombFrame.timerText.startTimer();
                    action.actLeftButton(bombFrame, id);
                } else if (mod == InputEvent.BUTTON3_MASK) {

                    if (action.checkGameOvered(bombFrame)) {
                        return;
                    }
                    
                    // Timer Start
                    bombFrame.timerText.startTimer();
                    action.actRightButton(bombFrame, id);
                }
                int finished = action.isFinished(bombFrame);

                String imagePath = null;
                if (finished == 0){
                    bombFrame.timerText.stopTimer();
                    imagePath = "/images/2.gif";
                    action.changeStartButtonImage(bombFrame, imagePath);

                    action.showModallog(frame, "Message", "Winner");
                    
                    // Save Score into XML file
                    doSaveScore();                    

                } else if (finished == -1){
                    bombFrame.timerText.stopTimer();
                    imagePath = "/images/9.gif";
                    action.changeStartButtonImage(bombFrame, imagePath);
                    // showDialog("Game Over!");
                    action.showModallog(frame, "Message", "Game Over!");
                }
                
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace();
            }
        }
    }

    /**
     * Button Action
     */
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();
        if (obj instanceof JButton) {
            JButton button = (JButton) obj;
            if ("START_BUTTON".equals(button.getName())) {
                MainBean mBean = getMainBean();
                new BombAction().actStartGame(mBean);
            }
        }
    }
}
